<script setup lang="tsx">
import { ref, inject, computed } from 'vue';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import QueryBox from '@/components/queryBox/index.vue';
import { formGroup } from '@/components/formDialog/FormDialog';
import FormDialogGroup from '@/components/formDialog/FormDialogGroup.vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { AddIcon, SearchIcon } from 'tdesign-icons-vue-next';
import { getList, add } from '@/api/yuebao/record';
import { getProductList } from '@/api/yuebao/product';
import { getName } from '@/utils/tool';
const addDateRange = inject<typeof addDateRange>('addDateRange');
const data = ref([]);
const columns = [
  {
    title: '用户名',
    colKey: 'username',
  },
  {
    title: '产品名称',
    colKey: 'yid',
  },
  {
    title: '利率',
    colKey: 'lilv',
  },
  {
    title: '金额',
    colKey: 'money',
    cell: (h: any, { row }: { row: any }) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(row.money || 0);
    },
  },
  {
    title: '天数',
    colKey: 'daynum',
  },
  {
    title: '代理',
    colKey: 'team',
  },
  {
    title: '管理员操作',
    colKey: 'status',
  },
  {
    title: '开始时间',
    colKey: 'startTime',
  },
  {
    title: '结束时间',
    colKey: 'endTime',
  },
];

const footData = computed(() => {
  const totalMoney = data.value.reduce((sum, item) => sum + (item.money || 0), 0);

  return [
    {
      username: '合计',
      // 格式化显示
      money: new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(totalMoney),
    },
  ];
});

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

interface FormDataType {
  username: string | null;
  yid: string | number | null;
  pageNum: string | number | null;
  pageSize: string | number | null;
}

const INITIAL_QUERYFORM: FormDataType = {
  username: undefined,
  yid: undefined,
  pageNum: null,
  pageSize: null,
};

const queryForm = ref({ ...INITIAL_QUERYFORM });

const dateRange = ref<string[]>([]);
const balanceRange = ref<[number | null, number | null]>([null, null]);
const render = () => (
  <>
    <OperatingBox>
      <t-button icon={() => <AddIcon />} onClick={() => unAdd()}>
        新增
      </t-button>
      <div>总笔数：{pagination.value.total}</div>
      <div>总金额：24998391</div>
    </OperatingBox>
    <QueryBox onReset={onReset} v-model:defaultCurrent={pagination.value.defaultCurrent} onSearch={unGetList}>
      <t-input v-model={queryForm.value.username} placeholder="用户名" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-date-range-picker v-model={dateRange.value} placeholder="开始时间" />
      <t-select v-model={queryForm.value.yid} placeholder="产品">
        {productList.value?.map((item) => <t-option key={item.yid} label={item.title} value={item.yid} />)}
      </t-select>
    </QueryBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      rowKey="id"
      onUnGetList={unGetList}
      footData={footData.value}
    >
      {{
        yid: (slotProps: any) => <div>{getName('yid', slotProps.row.yid, productList.value, 'title')}</div>,
        status: (slotProps: any) => (
          <t-tag theme={slotProps.row.status == 1 ? 'primary' : 'danger'} variant="light">
            {slotProps.row.status == 1 ? '是' : '否'}
          </t-tag>
        ),
      }}
    </MyTable>
  </>
);

const unGetList = async () => {
  try {
    queryForm.value.pageNum = pagination.value.defaultCurrent;
    queryForm.value.pageSize = pagination.value.defaultPageSize;
    const res = await getList({
      ...addDateRange?.(queryForm.value, dateRange.value),
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};

// 产品列表
const productList = ref([]);
const unGetProductList = async () => {
  try {
    const res = await getProductList({
      pageNum: 1,
      pageSize: 999,
    });
    productList.value = res.rows;
    unGetList();
  } catch (e) {
    console.log(e);
  }
};
unGetProductList();

const onReset = () => {
  queryForm.value = { ...INITIAL_QUERYFORM };
  balanceRange.value = [null, null];
  dateRange.value = [];
  unGetList();
};
/** 添加对话框 */
const formObj = new formGroup();
const unAdd = async () => {
  try {
    formObj.show('购买余额宝', {}, '购买余额宝');
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '购买余额宝',
  '购买余额宝',
  {},
  async (body) => {
    await add(body.data);
    unGetList();
  },
  {
    username: [{ required: true, message: '会员账号不能为空', trigger: 'blur' }],
    yid: [{ required: true, message: '产品不能为空', trigger: 'change' }],
    money: [{ required: true, message: '购买金额不能为空', trigger: 'blur' }],
  },
);
</script>

<template>
  <div>
    <render />
    <FormDialogGroup :form-obj="formObj">
      <template #default="{ formData, item }">
        <!-- 添加银行卡对话框 -->
        <template v-if="item == '购买余额宝'">
          <t-form-item label="账号" name="username">
            <t-input v-model="formData.username" placeholder="请输入账号" />
          </t-form-item>
          <t-form-item label="产品" name="yid">
            <t-select v-model="formData.yid" placeholder="请选择产品">
              <t-option v-for="item in productList" :key="item.yid" :label="item.title" :value="item.yid" />
            </t-select>
          </t-form-item>
          <t-form-item label="购买金额" name="money">
            <div class="capital">
              <t-input-number v-model="formData.money" placeholder="请输入购买金额" />
            </div>
          </t-form-item>
        </template>
      </template>
    </FormDialogGroup>
  </div>
</template>

<style lang="less" scoped>
.capital .t-input-number.t-input-number--row {
  width: 314px;
  display: flex;
  align-items: center;
  padding: 0 38px;

  .t-button.t-button--variant-outline.t-button--theme-default.t-button--shape-square.t-button--icon-only {
    width: 38px;
    height: 38px;
  }
}
</style>
<style>
.capital .t-input-number .t-input.t-align-center {
  width: 230px !important;
}
</style>
